﻿<%@ WebHandler Language="C#" Class="t" %>

using System;
using System.Web;
using MindTouch.Dream;
using System.Threading;
using System.Collections.Generic;
using Morange.Async;

public class t : IHttpAsyncHandler {
    private DateTime ts = DateTime.Now;
    
    public void ProcessRequest (HttpContext context) {
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    

    #region IHttpAsyncHandler Members

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
    { 
        //context.Response.Write("Begin: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "<br />");
        //AsyncCoreResult r;
        //r = AsyncCore.AddAsyncPage(context, cb, GetPage);
        //return r;
        return AsyncCore.AddAsyncPage(context, cb, GetPage, extraData);
    }

    public void EndProcessRequest(IAsyncResult result)
    {
        AsyncCoreResult r = (AsyncCoreResult)result;
        r.context.Response.Write("End: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "<br />");
        r.context.Response.Write(DateTime.Now.Subtract(ts).ToString());
    }

    #endregion

    public IEnumerator<IYield> GetPage(AsyncCoreResult r, Result result)
    {
        r.context.Response.Redirect("default.aspx", true);
        string url;
        url = r.context.Request.QueryString["url"];
        //url = r.context.Request["url"];
        if (string.IsNullOrEmpty(url))
        {
            url = "http://www.blogwind.com";
        }
        
        XUri uriToDownload = new XUri(url);
        r.context.Response.Write("1: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "<br />");
        Plug p = Plug.New(uriToDownload);
        Result<DreamMessage> res;
        yield return res = p.GetAsync();

        

        url = r.context.Request["url"];
        uriToDownload = new XUri(url);
        r.context.Response.Write("2: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "<br />");
        r.context.Response.Write("3: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "<br />");
        r.context.Response.Write("<textarea>");
        r.context.Response.Write(res.Value.AsText());
        r.context.Response.Write("</textarea>");
        r.context.Response.Write("<br />");
        
        
        r.cb(r);
    }
}